
import 'package:find_friend/common/alert_tool.dart';
import 'package:find_friend/common/event_bus.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:find_friend/pages/login&register/model/shared_user_info.dart';
import 'package:find_friend/pages/mine/model/tagmodel.dart';
import 'package:flutter/material.dart';

class MineTags extends StatefulWidget {

  final List<String> mineTags;

  const MineTags({Key key, this.mineTags}) : super(key: key); // 我的标签

  @override
  _MineTagsState createState() => _MineTagsState();
}

class _MineTagsState extends State<MineTags> {

  bool isupdate;
  List<String> list = [];
  List<String> tags = [];

  FocusNode _focusNode = FocusNode();
  TextEditingController _editingController = TextEditingController();
  bool isfocusNode = false;
  List<List<String>> res = [];

  @override
  void initState() {
    super.initState();
    tags = widget.mineTags;
    _focusNode.addListener(() { 
      setState(() {
        isfocusNode = _focusNode.hasFocus;
      });
    });

    // 检查是否含有自定义标签

    _updateTas();
    _requestTags();
  }

  _requestTags() {
    Networktool.request(API.sys_label, method: NETWORKHTTPMethod.GET, success: (data){
      if(data != null){
        TagsModel model = TagsModel.fromJson(data);
        list = model.data.map((e) => e.name).toList();
        // 检查是否含有自定义标签
        tags.forEach((element) { 
          if(!list.contains(element)) list.insert(0, element);
        });
        _updateTas();
      }
    });
  }

  _updateTas(){
    List<List<String>> temp = [];
    bool issecond = true;
    for(int i=0;i<list.length;i){
      var count = issecond ? 4 : 3;
      var xcount = i + count;
      if(xcount >= list.length) xcount = list.length - 1;
      final arr = list.sublist(i, xcount);
      temp.add(arr);
      i += count;
      issecond = !issecond;
    }
    res = temp;
    if(mounted) setState(() { });
  }

  _request() {
    String temp = tags.join(",");
    Networktool.request(API.edit, params: {"label": temp}, success: (data){
      print(data);
      if(data["data"] != null) {
        SharedUserInfo.saveData(data);
        AlertTool.showToast("修改成功");
        EventMineBus.instance.commit(EventMineKeys.UpdateMineInfo, null);
        Navigator.of(context).pop(true);
      }
    },
    fail: (msg) => AlertTool.showToast(msg));
  }
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      backgroundColor: APP_scaffold_back_color,
      appBar: AppBar(
        title: Text("我的标签"),
        backgroundColor: Colors.white,
        centerTitle: true,
        leading: IconButton(
          onPressed: (){
            Navigator.of(context).pop(isupdate);
          },
          icon: Image.asset("assets/fanhui.png"),
        ),
        actions: [
          FlatButton(
            splashColor: Colors.transparent,
            highlightColor: Colors.transparent,
            onPressed: _request,
            child: Container(
              decoration: BoxDecoration(
                color: APP_main_color,
                borderRadius: BorderRadius.circular(20)
              ),
              padding: const EdgeInsets.symmetric(horizontal: 11, vertical: 4),
              child: Text("提交", style: instanceTextStyle(14, Colors.white),),
            ),
          )
        ],
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemCount: res.length,
              itemBuilder: (context, index){
                return _RowTag(list: res[index],tags: tags,);
              }
            ),
          ),
          Stack(
            children: [
              Offstage(
                offstage: isfocusNode,
                child: Center(
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 45, vertical: 5),
                    margin: EdgeInsets.only(bottom: isfocusNode ? 0 : 45),
                    decoration: BoxDecoration(
                      border: Border.all(color: APP_font_black, width: 1.5),
                      borderRadius: BorderRadius.circular(20)
                    ),
                    child: Text("自定义标签"),
                  ),
                ),
              ),
              Opacity(
                opacity: isfocusNode ? 1 : 0,
                child: Container(
                  margin: const EdgeInsets.symmetric(horizontal: 10),
                  height: 45,
                  child: TextField(
                    controller: _editingController,
                    maxLength: 4,
                    onSubmitted: (val) => _focusNode.unfocus(),
                    decoration:InputDecoration(
                          hintText: "请输入标签名称",
                          counterText: "",
                          focusedBorder: OutlineInputBorder(
                          borderRadius: const BorderRadius.all(Radius.circular(25)),
                          borderSide: const BorderSide(width: 1.5, color: Colors.black),
                        ),
                        enabledBorder: OutlineInputBorder(
                          borderRadius: const BorderRadius.all(Radius.circular(25)),
                          borderSide: const BorderSide(width: 1.5, color: Colors.black),
                        ),
                        border: OutlineInputBorder(
                          borderRadius: const BorderRadius.all(Radius.circular(25)),
                          borderSide: const BorderSide(width: 1.5, color: Colors.black),
                        ),
                        contentPadding: const EdgeInsets.only(left: 14, right: 14),
                        suffix: GestureDetector(
                          onTap: (){
                            if(_editingController.text == "") _focusNode.unfocus();
                            list.insert(0, _editingController.text);
                            _updateTas();
                            _focusNode.unfocus();
                            _editingController.clear();
                          },
                          child: Container(
                            padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 4),
                            decoration: BoxDecoration(
                              color: APP_main_color,
                              borderRadius: BorderRadius.circular(20)
                            ),
                            child: Text("添加", style: instanceTextStyle(14, Colors.white),)
                          ),
                        )
                    ),
                    focusNode: _focusNode,
                    autofocus: false,
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

class _RowTag extends StatelessWidget {

  final List<String> list;
  final List<String> tags;

  const _RowTag({Key key, this.list, this.tags}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(top: 10.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: list.map((e) =>
          _TagButtonWidget(title: e, tags: tags,)
        ).toList(),
      ),
    );
  }
}

class _TagButtonWidget extends StatefulWidget {
  
  final String title;
  final List<String> tags;

  const _TagButtonWidget({Key key, this.title, this.tags}) : super(key: key);

  @override
  __TagButtonWidgetState createState() => __TagButtonWidgetState();
}

class __TagButtonWidgetState extends State<_TagButtonWidget> {

  bool isselect = false;

  @override
  void initState() {
    super.initState();
    _updateTags();
  }

  _updateTags() {
    setState(() {
      isselect = widget.tags.contains(widget.title);
    });
  }

  @override
  Widget build(BuildContext context) {
    
    final size = MediaQuery.of(context).size;
    final width = (size.width - 50) / 4.0;
    
    return InkWell(
      onTap: (){
        if(isselect){
          widget.tags.remove(widget.title);
        } else {
          widget.tags.add(widget.title);
        }
        _updateTags();
      },
      child: Container(
        width: width,
        padding: const EdgeInsets.symmetric(vertical: 5.6),
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: isselect ? APP_main_color : APP_scaffold_back_color,
          borderRadius: BorderRadius.circular(20),
          border: Border.all(color: APP_font_black, width: 1.5)
        ),
        child: Text(widget.title, style: instanceTextStyle(12, isselect ? Colors.white : APP_font_black),),
      ),
    );
  }
}